package com.bkgy.modular.tbChangerRollTcm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baosight.hdsdk.domain.data.HDDataConnection;
import com.baosight.hdsdk.exception.HDSdkException;
import com.bkgy.modular.tbChangerRollTcm.entity.IntermediateTable;
import com.bkgy.modular.tbChangerRollTcm.entity.TbChangerRollTcm;
import com.bkgy.modular.tbChangerRollTcm.mapper.IntermediateTableMapper;
import com.bkgy.modular.tbChangerRollTcm.mapper.TbChangerRollTcmMapper;
import com.bkgy.modular.tbdsjdatacollect.dao.TbDsjDataCollectDao;
import com.bkgy.modular.tbdsjdatacollect.entity.TbDsjDataCollect;
import com.bkgy.util.SDKUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author
 * @version 1.0
 * @ClassName TbChangerRollTcmService
 * @date 2023/6/7 17:04
 */
@Service
@Slf4j
public class TbChangerRollTcmServiceImpl implements ApplicationContextAware {
    @Resource
    private TbChangerRollTcmMapper tbChangerRollTcmMapper;

    @Resource
    private SDKUtils sdkUtils;

    @Resource
    private TbDsjDataCollectDao tbDsjDataCollectDao;

    @Resource
    private IntermediateTableMapper intermediateTableMapper;

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    //@Scheduled(cron = "${c621Time}")
    public void saveChangerRollTcmData() {
        log.error("TbChangerRollTcmServiceImpl+saveChangerRollTcmData");
        try {
            // 获取连接
            HDDataConnection connect = sdkUtils.getConnect();
            while (!connect.isConnected()) {
                connect = sdkUtils.getConnect();
            }
            //查找需要查询的sdk变量名，别名
            LambdaQueryWrapper<TbDsjDataCollect> tbDsjDataCollectLambdaQueryWrapper = new LambdaQueryWrapper<>();
            tbDsjDataCollectLambdaQueryWrapper.eq(TbDsjDataCollect::getOut_data_source, "3")
                    .and(item -> item.eq(TbDsjDataCollect::getProduction_line, "C621").or()
                            .eq(TbDsjDataCollect::getProduction_line, "C622"));
            List<TbDsjDataCollect> tbDsjDataCollectList = tbDsjDataCollectDao.selectList(tbDsjDataCollectLambdaQueryWrapper);

            // 查询出所有中间表数据
            List<IntermediateTable> intermediateTableList = intermediateTableMapper.selectList(null);

            // 遍历tbDsjDataCollect集合查询出每个变量名的tagId
            for (TbDsjDataCollect collect : tbDsjDataCollectList) {
                // 使用变量名查询宝信相对应的数据值
                Integer tagId = sdkUtils.findTagId(collect.getL1_variable_name(), connect.getTagManager());
                String dataOneById = sdkUtils.findDataOneById(tagId, connect.getDataProvider());
                // 中间表数据不为空,本次宝信辊号与中间表一一对比
                for (IntermediateTable intermediateTable : intermediateTableList) {
                    // 根据变量名进行判断
                    if (intermediateTable.getL1_variable_name().equals(collect.getL1_variable_name())) {
                        // 判断本次宝信辊号与中间表辊号是否一致
                        if (!intermediateTable.getData_value().equals(dataOneById)) {
                            log.error("当前辊号与上次辊号不一样" + ":当前辊号" + dataOneById + ",上次辊号" + intermediateTable.getData_value());

                            // 当前系统时间
                            LocalDateTime endLocalDateTime = LocalDateTime.now();

                            // 查询上条数据
                            LambdaQueryWrapper<TbChangerRollTcm> tbChangerRollTcmLambdaQueryWrapper = new LambdaQueryWrapper<>();
                            // 状态为0,下机时间为null的数据
                            tbChangerRollTcmLambdaQueryWrapper.and(item ->
                                    item.eq(TbChangerRollTcm::getStauts, "0")
                                            .eq(TbChangerRollTcm::getRoll_id, intermediateTable.getData_value())
                                            .isNull(TbChangerRollTcm::getOffline_time));

                            //其实只能找出一条，并且修改数值（下线时间，在机状态）
                            List<TbChangerRollTcm> tbChangerRollTcmList = tbChangerRollTcmMapper.selectList(tbChangerRollTcmLambdaQueryWrapper);
                            if (!tbChangerRollTcmList.isEmpty()) {
                                for (TbChangerRollTcm tbChangerRollTcm : tbChangerRollTcmList) {
                                    tbChangerRollTcm.setOffline_time(Timestamp.valueOf(endLocalDateTime));
                                    tbChangerRollTcm.setStauts(Double.parseDouble("1"));
                                    tbChangerRollTcmMapper.update(tbChangerRollTcm, tbChangerRollTcmLambdaQueryWrapper);
                                }
                            }

                            // 插入当前数据
                            TbChangerRollTcm tbChangerRollTcm2 = new TbChangerRollTcm();
                            tbChangerRollTcm2.setLinecode(intermediateTable.getProduction_line());
                            tbChangerRollTcm2.setStand(collect.getDevice_code());
                            tbChangerRollTcm2.setPos(collect.getArea_code());
                            tbChangerRollTcm2.setOnline_time(Timestamp.valueOf(endLocalDateTime));
                            tbChangerRollTcm2.setRoll_id(dataOneById);
                            tbChangerRollTcmMapper.insert(tbChangerRollTcm2);


                            // 不一致先更新中间表,在保存到最终的TB_CHANGER_ROLL_TCM表中,并更新上条数据的下机时间
                            LambdaQueryWrapper<IntermediateTable> queryWrapper = new LambdaQueryWrapper<>();
                            queryWrapper.and(item ->
                                    item.eq(IntermediateTable::getProduction_line, collect.getProduction_line())
                                            .eq(IntermediateTable::getL1_variable_name, collect.getL1_variable_name()));
                            intermediateTable.setData_value(dataOneById);
                            intermediateTableMapper.update(intermediateTable, queryWrapper);
                        } else {
                            break;
                        }
                    }
                }
            }
            try {
                connect.dispose();
            } catch (HDSdkException e) {
                log.error("AlarmService300+startAlarm300+connect释放失败");
            }
        } catch (Exception e) {
            log.error("TbChangerRollTcmServiceImpl+saveChangerRollTcmData:中间有错误");
            //e.printStackTrace();
        }
    }
}
